// FLTK Image class which preserves aspect ratio when drawing
// Copyright 2005 (C) Ralph Thomas

#include <toolkit/fltk/aspectImage.h>

namespace fltk {
	AspectImage::AspectImage() : _source( 0 ) {}
	AspectImage::~AspectImage() {}
	void AspectImage::setSource( fltk::Image* source ) { _source = source; }
	void AspectImage::_measure( int& w, int& h ) const {
		if( !_source ) { w = 0; h = 0; return; }
		_source->measure( w, h );
	}
	void AspectImage::_draw( const fltk::Rectangle& target ) const {
		fltk::Rectangle r( target );
		if( !_source ) return;
		//
		// Preserve the image's aspect ratio.
		//
		int imw( r.w() );
		int imh( r.h() );
		_source->measure( imw, imh );
		//
		// Figure out which our smallest normalized dimension is.
		//
		double dw( (double)imw / (double)r.w() );
		double dh( (double)imh / (double)r.h() );

		if( dw > dh ) {
			int rh( r.h() );
			r.h( (int)((double)r.w() *
				((double)imh / (double)imw)) );
			r.y( r.y() + (rh - r.h()) / 2 );
		} else {
			int rw( r.w() );
			r.w( (int)((double)r.h() *
				((double)imw / (double)imh)) );
			r.x( r.x() + (rw - r.w()) / 2 );
		}
		_source->_draw( r );
	}
	void AspectImage::update() { if( _source ) _source->update(); }
};

